package common.config.feign;

import cn.hutool.json.JSONUtil;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import common.config.exception.CustomException;
import common.model.response.base.Result;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * Feign熔断配置<p>
 * 不进入熔断处理
 *
 * @author 米泽鹏
 * @since 2023-8-11 下午 3:55
 */
@Configuration
@Slf4j
public class NotBreakerConfiguration extends ErrorDecoder.Default {

	@Override
	public Exception decode(String methodKey, Response response) {
		Exception exception = null;
		try {
			// 获取原始返回内容
			String json = IOUtils.toString(response.body().asReader());
			exception = new CustomException(json);
			Result<?> result = JSONUtil.toBean(json, Result.class);
			// 业务异常包装成HystrixBadRequestException，不进入熔断逻辑
			if (result.wasFailed()) {
				exception = new HystrixBadRequestException(result.getMessage());
				log.warn("feign调用返回失败结果，不进入熔断：{}", result.getMessage());
			}
		} catch (IOException ex) {
			log.error(ex.getMessage(), ex);
		}
		return exception;
	}

}
